package com.bolingcavalry.crm.summaryorder.service.impl;

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.*;

/**
 *
 */
public class TableParser {

    public static List<Map<String, String>> extractReplacementDetails(JSONArray body) {
        List<Map<String, String>> result = new ArrayList<>();
        int index = 0;

        // 查找【更换明细】的位置
        while (index < body.length()) {
            JSONObject cell = body.getJSONObject(index);
            if ("更换明细".equals(cell.optString("words", "").trim())) {
                index += 1; // 跳过“更换明细”
                break;
            }
            index++;
        }

        if (index >= body.length()) {
            System.out.println("未找到【更换明细】");
            return result;
        }

        // 跳过列名（如“名称、规格、数量、单价（元）”）
        index += 4;

        // 每次读取四个字段，直到遇到“合计”
        while (index < body.length()) {
            JSONObject nameCell = body.getJSONObject(index++);
            JSONObject specCell = body.getJSONObject(index++);
            JSONObject quantityCell = body.getJSONObject(index++);
            JSONObject priceCell = body.getJSONObject(index++);

            String name = nameCell.optString("words", "").trim();
            String spec = specCell.optString("words", "").trim();
            String quantity = quantityCell.optString("words", "").trim();
            String price = priceCell.optString("words", "").trim();

            // 遇到“合计”就停止
            if ("合计".equals(name)) {
                break;
            }

            // 只添加不全为空的行
            if (!name.isEmpty() || !spec.isEmpty() || !quantity.isEmpty() || !price.isEmpty()) {
                Map<String, String> rowMap = new HashMap<>();
                rowMap.put("名称", name);
                rowMap.put("规格", spec);
                rowMap.put("数量", quantity);
                rowMap.put("单价（元）", price);

                result.add(rowMap);
            }
        }

        return result;
    }
}